package com.fhz.day015;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * 时间:2022/6/2
 *
 * @author msfeng
 * 简述: TODO
 */
public class MyViewGroup extends ViewGroup {

    //距离左的距离
    int left = 0;
    //距离顶部的距离
    int top = 0;
    //所有子布局的总长度
    int curLen =0;

    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = getChildAt(i);
            //测量子布局
            measureChild(childAt,widthMeasureSpec,heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //控制子布局如何拜访.

        //得到多少个view
        int childCount = getChildCount();

        /**
         * 整体思路是:
         * 第一个view正常布局.不管如何都是定边放置
         * 从第二个view开始. 要判断总长度.能放下 ,就放到一行.
         * 放不下的情况,要从头开始放置.
         * 不同的放置,就是调整left.和 top的位置.  让宽+left 和 高加top 即可.
         *
         */
        for (int j = 0; j < childCount; j++) {
            View childAt = getChildAt(j);
            //第一个view
            if(j == 0){
                childAt.layout(left, top, childAt.getMeasuredWidth(), childAt.getMeasuredHeight());
                left += childAt.getMeasuredWidth();
                curLen = childAt.getMeasuredWidth();
                continue;
            }

            //目前横排摆放的长度
            curLen += childAt.getMeasuredWidth();
            if(curLen  < getMeasuredWidth()){
                childAt.layout(left, top, childAt.getMeasuredWidth() + left, childAt.getMeasuredHeight()+top);
                left += childAt.getMeasuredWidth();
            }else{
                //换行以后. left和top都要重新排布.
                left = 0;
                curLen = childAt.getMeasuredWidth();
                top += childAt.getMeasuredHeight();
                childAt.layout(left, top, childAt.getMeasuredWidth() + left, childAt.getMeasuredHeight()+top);
                left += childAt.getMeasuredWidth();
            }
        }

    }
}

